package org.zyzboole.base.encrypt.plugins;

import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.zyzboole.base.encrypt.core.OriginalFiledDTO;
import org.zyzboole.base.encrypt.properties.EnCryptProperties;
import org.zyzboole.base.encrypt.rewrite.EncryptPreParameterRewriter;

import java.sql.Statement;
import java.util.List;
import java.util.Properties;

/**
 * @author liangwx
 */
@Slf4j
@Intercepts({
        @Signature(type = StatementHandler.class, method = "parameterize", args = Statement.class)
})
public class EnCryptInterceptor implements Interceptor {

    private final EncryptPreParameterRewriter rewriter;

    public EnCryptInterceptor(EnCryptProperties properties) {
        this.rewriter = new EncryptPreParameterRewriter(properties);
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object target = PluginUtils.realTarget(invocation.getTarget());
        MetaObject metaObject = SystemMetaObject.forObject(target);
        String sql = (String) metaObject.getValue("delegate.boundSql.sql");
        List<ParameterMapping> parameterMappings = (List<ParameterMapping>) metaObject.getValue("delegate.boundSql.parameterMappings");
        Object parameterObject = metaObject.getValue("delegate.boundSql.parameterObject");
        MetaObject metaObjects = SystemMetaObject.forObject(parameterObject);

        List<OriginalFiledDTO> rewrite = rewriter.rewrite(sql, parameterMappings, metaObjects);
        Object returnObj = invocation.proceed();
        metaObjects.getOriginalObject();
        // 恢复加密前数据
        rewrite.forEach(item -> {
            metaObjects.setValue(item.getOriginalColumn(), item.getOriginalValue());
        });
        return returnObj;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
